<template>
  <a-modal
    :title="title"
    :width="900"
    :visible="visible"
    :footer="null"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
    cancelText="关闭">

    <a-spin :spinning="confirmLoading">
      <a-card :bordered="false">
        <a-steps class="steps" size="small" labelPlacement="vertical" :current="currentTab" >
          <a-step title="商品信息" />
          <a-step title="商品属性" />
          <a-step title="销售信息" />
          <a-step title="商品详情" />
        </a-steps>
        <div class="content">
          <product-info-detail v-model="model" ref="infoDetail" v-if="currentTab === 0" @nextStep="nextStep"/>
          <product-attr-detail v-model="model" ref="attrDetail" v-if="currentTab === 1" @nextStep="nextStep" @prevStep="prevStep"/>
          <product-sale-detail v-model="model" ref="saleDetail" v-if="currentTab === 2" @nextStep="nextStep" @prevStep="prevStep"/>
          <product-html-detail v-model="model" ref="htmlDetail" v-if="currentTab === 3" @prevStep="prevStep" @finish="finish"/>
        </div>
      </a-card>
    </a-spin>
  </a-modal>
</template>

<script>
  import { httpAction } from '@/api/manage'
  import { getAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import moment from "moment"
  import ProductInfoDetail from './productForm/ProductInfoDetail'
  import ProductSaleDetail from './productForm/ProductSaleDetail'
  import ProductHtmlDetail from './productForm/ProductHtmlDetail'
  import ProductAttrDetail from './productForm/ProductAttrDetail'

  const defaultProductParam = {
    albumPics: '',
    brandId: '',
    brandName: '',
    deleteStatus: 0,
    description: '',
    detailDesc: '',
    detailHtml: '',
    detailMobileHtml: '',
    detailTitle: '',
    feightTemplateId: 0,
    flashPromotionCount: 0,
    flashPromotionId: 0,
    flashPromotionPrice: 0,
    flashPromotionSort: 0,
    giftPoint: 0,
    giftGrowth: 0,
    keywords: '',
    lowStock: 0,
    name: '',
    skuName: '',
    newStatus: '0',
    hotStatus: '0',
    note: '',
    originalPrice: 0,
    pic: '',
    //会员价格{memberLevelId: 0,memberPrice: 0,memberLevelName: null}
    memberPriceList: [],
    //商品满减
    productFullReductionList: [{fullPrice: 0, reducePrice: 0}],
    //商品阶梯价格
    productLadderList: [{count: 0,discount: 0,price: 0}],
    previewStatus: '0',
    price: 0,
    productAttributeCategoryId: '',
    //商品属性相关
    attrList: [],
    paramList: [],
    //商品sku库存信息{lowStock: 0, pic: '', price: 0, sale: 0, skuCode: '', sp1: '', sp2: '', sp3: '', stock: 0}
    skuStockList: [],
    //商品相关专题{subjectId: 0}
    subjectProductRelationList: [],
    //商品相关优选{prefrenceAreaId: 0}
    prefrenceAreaProductRelationList: [],
    productCategoryId: '',
    productCategoryName: '',
    productSn: '',
    promotionEndTime: '',
    promotionPerLimit: 0,
    promotionPrice: null,
    promotionStartTime: '',
    promotionType: '0',
    publishStatus: '0',
    recommandStatus: '0',
    sale: 0,
    serviceIds: '',
    serviceOptions: [],
    sort: 0,
    stock: 0,
    subTitle: '',
    unit: '',
    usePointLimit: 0,
    verifyStatus: 0,
    weight: 0,
    color: ''
  };
  export default {
    name: "PmsProductModal",
    components: {
      ProductSaleDetail,
      ProductInfoDetail,
      ProductHtmlDetail,
      ProductAttrDetail
    },
    data () {
      return {
        currentTab: 0,
        //productParam: Object.assign({}, defaultProductParam),
        // form
        form: null,
        title:"操作",
        visible: false,
        model: {},
        //商品属性
        selectProductAttr: [],
        //商品参数
        selectProductParam: [],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },

        confirmLoading: false,
        url: {
          add: "/pms/pmsProduct/add",
          edit: "/pms/pmsProduct/edit",
          queryAttr: '/pms/pmsProduct/queryAttrById',
          queryByProductCategoryId: '/pms/pmsProductTag/queryByProductCategoryId',
        },
      }
    },
    created () {
    },
    methods: {
      getProductAttrListByEdit() {
        if(this.model.productAttributeCategoryId === undefined || this.model.productAttributeCategoryId === null || this.model.productAttributeCategoryId === ''){
          return;
        }
        this.selectProductAttr = [];
        this.selectProductParam = [];
        getAction(this.url.queryAttr,{id:this.model.productAttributeCategoryId, productId:this.model.id}).then(res=>{
          if(res.success){
            let list = res.result;
            for (let i = 0; i < list.length; i++) {
              if(this.model.id === undefined || this.model.id === null || this.model.id === '' ){
                list[i].value = '';
              }
              if (list[i].type === '0') {
                this.selectProductAttr.push(list[i]);
              } else {
                this.selectProductParam.push(list[i]);
              }
            }
            this.model.attrList = this.selectProductAttr;
            this.model.paramList = this.selectProductParam;
          }else{
            console.log(res.message);
          }
        });
      },
      getServiceOptions() {
        if(this.model.productCategoryId === undefined || this.model.productCategoryId === null || this.model.productCategoryId === ''){
          return;
        }
        getAction(this.url.queryByProductCategoryId,{productCategoryId:this.model.productCategoryId}).then(res=>{
          if (res.success) {
            this.model.serviceOptions = res.result.map(data => ({ label: data['name'], value: data['id'] }));
            //console.log('serviceOptions：' + this.model.serviceOptions[0].label + ' : ' + this.model.serviceOptions[0].value);
          }
        });
      },
      add () {
        this.selectProductAttr = [];
        this.selectProductParam = [];
        this.edit(defaultProductParam);
      },
      edit (record) {
        this.currentTab = 0;
        //this.form.resetFields();
        this.model = Object.assign({}, record);
        this.model.serviceOptions = [];
        this.visible = true;
        if(this.model.productAttributeCategoryId !== ''){
          this.getProductAttrListByEdit();
        }
        if (this.model.productCategoryId !== '') {
          this.getServiceOptions();
        }
        this.$nextTick(() => {
          //this.$refs.infoDetail.form.setFieldsValue(pick(this.model,'brandId','productCategoryId','feightTemplateId','productAttributeCategoryId','name','pic','productSn','deleteStatus','publishStatus','newStatus','recommandStatus','verifyStatus','sort','sale','price','promotionPrice','giftGrowth','giftPoint','usePointLimit','subTitle','description','originalPrice','stock','lowStock','unit','weight','previewStatus','serviceIds','keywords','note','albumPics','detailTitle','detailDesc','detailHtml','detailMobileHtml','promotionPerLimit','promotionType','brandName','productCategoryName'))
          //this.$refs.saleDetail.form.setFieldsValue(pick(this.model,'brandId','productCategoryId','feightTemplateId','productAttributeCategoryId','name','pic','productSn','deleteStatus','publishStatus','newStatus','recommandStatus','verifyStatus','sort','sale','price','promotionPrice','giftGrowth','giftPoint','usePointLimit','subTitle','description','originalPrice','stock','lowStock','unit','weight','previewStatus','serviceIds','keywords','note','albumPics','detailTitle','detailDesc','detailHtml','detailMobileHtml','promotionPerLimit','promotionType','brandName','productCategoryName'))
          //this.form.setFieldsValue(pick(this.model,'brandId','productCategoryId','feightTemplateId','productAttributeCategoryId','name','pic','productSn','deleteStatus','publishStatus','newStatus','recommandStatus','verifyStatus','sort','sale','price','promotionPrice','giftGrowth','giftPoint','usePointLimit','subTitle','description','originalPrice','stock','lowStock','unit','weight','previewStatus','serviceIds','keywords','note','albumPics','detailTitle','detailDesc','detailHtml','detailMobileHtml','promotionPerLimit','promotionType','brandName','productCategoryName'))
		      //时间格式化
          //this.form.setFieldsValue({promotionStartTime:this.model.promotionStartTime?moment(this.model.promotionStartTime):null})
          //this.form.setFieldsValue({promotionEndTime:this.model.promotionEndTime?moment(this.model.promotionEndTime):null})
        });
      },
      close () {
        this.$emit('close');
        this.visible = false;
      },
      handleOk () {
        const that = this;
        var snReg = /^[0-9A-Z]+$/
        var snRe = new RegExp(snReg)
        if (!snRe.test(this.model.productSn)) {
          that.$message.warning('商品货号不符合规则，只能是大写字母与数字');
          return;
        }

        that.confirmLoading = true;
        let httpurl = '';
        let method = '';
        if(!this.model.id){
          httpurl+=this.url.add;
          method = 'post';
        }else{
          httpurl+=this.url.edit;
          method = 'put';
        }
        this.model.detailMobileHtml = this.model.detailHtml;
        //let formData = Object.assign(this.model, values);
        //时间格式化
        //formData.promotionStartTime = formData.promotionStartTime?formData.promotionStartTime.format('YYYY-MM-DD HH:mm:ss'):null;
        //formData.promotionEndTime = formData.promotionEndTime?formData.promotionEndTime.format('YYYY-MM-DD HH:mm:ss'):null;

        //this.model.promotionStartTime = this.model.promotionStartTime?this.model.promotionStartTime.format('YYYY-MM-DD HH:mm:ss'):null;
        //this.model.promotionEndTime = this.model.promotionEndTime?this.model.promotionEndTime.format('YYYY-MM-DD HH:mm:ss'):null;

        httpAction(httpurl,this.model,method).then((res)=>{
          if(res.success){
            that.$message.success(res.message);
            that.$emit('ok');
            that.close();
          }else{
            that.$message.warning(res.message);
          }
        }).finally(() => {
          that.confirmLoading = false;
        })


        // 触发表单验证
        /*this.form.validateFields((err, values) => {
          if (!err) {

          }
        })*/
      },
      handleCancel () {
        this.close()
      },
      // handler
      nextStep () {
        if (this.currentTab < 3) {
          this.currentTab += 1
        }
      },
      prevStep () {
        if (this.currentTab > 0) {
          this.currentTab -= 1
        }
      },
      finish () {
        this.handleOk();
        //this.currentTab = 0;
      }
    }
  }
</script>

<style lang="less" scoped>
  .steps {
    max-width: 900px;
    margin: 16px auto;
  }
</style>